package com.facebook.android;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.FacebookActivity.SampleUploadListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.gfestival.GFestivalApplication;
import android.app.gfestival.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;



public class CamaraView extends Activity implements SurfaceHolder.Callback,
		OnClickListener {
	static final int FOTO_MODE = 0;
	private static final String TAG = "CameraTest";
	Camera mCamera;
	boolean mPreviewRunning = false;
	private Context mContext = this;
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private GFestivalApplication app;
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Log.e(TAG, "onCreate");
		
		Bundle extras = getIntent().getExtras();
		

		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.surface_camera);
		mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
		mSurfaceView.setOnClickListener(this);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
	 	mFacebook = new Facebook(FacebookActivity.APP_ID);
       	mAsyncRunner = new AsyncFacebookRunner(mFacebook);
       	SessionStore.restore(mFacebook, this);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	private ProgressDialog progress;
	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

		public void onPictureTaken(byte[] imageData, Camera c) {

			if (imageData != null) {
				Bundle params = new Bundle();
		        params.putString("method", "photos.upload");
		        BitmapDrawable bm = new BitmapDrawable(new ByteArrayInputStream(imageData));
		        ByteArrayOutputStream out = new ByteArrayOutputStream();
		        bm.getBitmap().compress(CompressFormat.JPEG, 80, out);
		        bm.getBitmap().recycle();
		        
//	            params.putByteArray("picture", Base64.encode(out.toByteArray(), Base64.DEFAULT));
//	            progress = showProgressDialog();
//	            mAsyncRunner.request(null, params, "POST",new SampleUploadListener(), null);
				Log.i("", "------------> take pic");
				Intent mIntent = getIntent();
				mIntent.putExtra("image", imageData);
				setResult(RESULT_OK,mIntent);
				finish();
				Log.i("", "------------> finish");
			}
		}
	};
	
	public ProgressDialog showProgressDialog() {
		ProgressDialog progress = new ProgressDialog(this, R.style.ProgressDialogSpinner);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage("Uploading...");
		progress.show();
		return progress;
	}
	
	public class SampleUploadListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: (executed in background thread)
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String src = json.getString("src");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                CamaraView.this.runOnUiThread(new Runnable() {
                    public void run() {
                    	Intent mIntent = getIntent();
        				mIntent.putExtra("image", "The photo has been uploaded at \n" + src);
        				setResult(RESULT_OK,mIntent);
        				progress.dismiss();
        				finish();
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }

	protected void onResume() {
		Log.e(TAG, "onResume");
		super.onResume();
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	protected void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(TAG, "surfaceCreated");
		mCamera = Camera.open();
	
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		Log.e(TAG, "surfaceChanged");

		// XXX stopPreview() will crash if preview is not running
		if (mPreviewRunning) {
			mCamera.stopPreview();
		}

		Camera.Parameters p = mCamera.getParameters();
		p.setPreviewSize(w, h);
		mCamera.setParameters(p);
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mCamera.startPreview();
		mPreviewRunning = true;
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.e(TAG, "surfaceDestroyed");
		mCamera.stopPreview();
		mPreviewRunning = false;
		mCamera.release();
	}

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	public void onClick(View arg0) {

		mCamera.takePicture(null, mPictureCallback, mPictureCallback);

	}

}